/**
 * 
 */
package abstractions;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Vector;

import static server.Server.*;


/**
 * @author rdru
 * INV: 
 */
public class OpenDoc extends UnicastRemoteObject  implements OpenDocInterface, Serializable {		// used by the Client
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public int							id;			// docId
	protected String					text;		// contents of the document
	public LinkedList<Integer>			editedBy;	// <userId, Usr>
	public Vector<LinkedList<CommandC>>	histOld;
	public HashMap<AtomId, Integer>		locked;		// <AtomId, userId>
	public LinkedList<Atom>				al;			// lista de atomos
	public HashMap<AtomId, Atom>		atomizer;	// cruzando atomos e seus respectivos atomIDs
	public int							atoms;		// number of atoms
	public int							ups;		// # updates sent
	public int							upr;		// # updates recieved
	public int							n;			// total # Commands recieved
	
	public OpenDoc(Doc d, String text) throws RemoteException {
		//super(d.fileName, d.pathName, d.isRemote);
		this.text = text;
		this.id = nextDocId++;
		this.editedBy = new LinkedList<Integer>();
		this.histOld  = new Vector<LinkedList<CommandC>>();
		this.locked   = new HashMap<AtomId, Integer>();
		this.al       = new LinkedList<Atom>();
		this.atomizer = new HashMap<AtomId, Atom>();
		String[] preatoms = text.split("\n");
		this.atoms = preatoms.length;
		Atom at;
		for (int i=1 ; i<=this.atoms ; i++){
			at = new Atom(new AtomId(new ArrayList<Integer>(i)),0, preatoms[i-1]);//at = new Atom(i,null, preatoms[i]);
			al.add(at);
			atomizer.put(at.id, at);
		}
		this.ups = 0;
		this.upr = 0;
		this.n = 0;
		
	}
	
	public void addUser(LoggedUser user) {
		editedBy.add(user.id);
	}
	
	public void removeUser(LoggedUser user) {
		if(editedBy.remove(user.id) == null) {
			// problems removing from editingUsers
		}
	}
}


